package com.mtaite.study.mybatis.controller;

import com.mtaite.study.mybatis.vo.UserVO;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/users")
public class UserRestController {
    Map<String,UserVO> users = new HashMap<>();

    @PostConstruct
    public void init() throws Exception{
        users.put("1",new UserVO("1","liqin","'md500232'"));
        users.put("2",new UserVO("2","liqin","'md500232'"));
    }

    /**
     * 获取所有用户
     * */
    @GetMapping("/list")
    public Flux<UserVO> getAll(){
        return Flux.fromIterable(users.entrySet().stream()
                .map(entry->entry.getValue())
                .collect(Collectors.toList()));
    }
    /**
     * 获取单个用户
     **/
    @RequestMapping("/get/{id}")
    public Mono<UserVO> getUser(@PathVariable String id){
        return Mono.justOrEmpty(users.get(id));
    }

    /**
     * 创建用户
     * **/
    @PostMapping("/add")
    public Mono<ResponseEntity<String>>  addUser(@RequestBody  UserVO user){
        users.put(user.getId(),user);
        return Mono.just(new ResponseEntity<>("添加成功", HttpStatus.CREATED));
    }

    /**
     * 删除用户
     * **/
    @DeleteMapping("/{id}")
    public Mono<ResponseEntity<String>> deleteUser(@PathVariable String id){
        users.remove(id);
        return Mono.just(new ResponseEntity<>("删除成功",HttpStatus.ACCEPTED));
    }
}